import { logger } from '#src/common/utils/logger.js';
import { ResponseHandler } from '#src/common/utils/http/responseHandler.js';
import { HTTP_STATUS } from '#src/constants/http.constants.js';
import { CommonMessage } from '#src/constants/message.constants.js';
// 修复目录导入问题，显式引用index.js
import { AppError, ValidationError, NotFoundError, AuthenticationError, ForbiddenError } from '#src/common/errors/index.js';

/**
 * 统一错误处理函数
 * @param {Error} error - 错误对象
 * @param {string} context - 错误上下文
 * @param {Object} logData - 额外的日志数据
 */
export function handleError(error, context, logData = {}) {
    const requestId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    
    // 移除无效的executionTime计算
    const errorContext = {
        context,
        requestId,
        code: error.code,
        message: error.message,
        stack: process.env.NODE_ENV !== 'production' ? error.stack : undefined,
        ...logData
    };

    // 错误处理配置映射表 - 提升可维护性
    const errorConfigMap = new Map([
        [NotFoundError, {
            type: 'RESOURCE_NOT_FOUND',
            level: 'warn',
            code: HTTP_STATUS.NOT_FOUND,
            message: CommonMessage.RESOURCE_NOT_FOUND
        }],
        [AuthenticationError, {
            type: 'AUTHENTICATION_ERROR',
            level: 'warn',
            code: HTTP_STATUS.UNAUTHORIZED,
            message: CommonMessage.AUTHENTICATION_REQUIRED
        }],
        [ForbiddenError, {
            type: 'FORBIDDEN_ERROR',
            level: 'warn',
            code: HTTP_STATUS.FORBIDDEN,
            message: CommonMessage.ACCESS_DENIED
        }],
        [ValidationError, {
            type: 'VALIDATION_ERROR',
            level: 'info',
            code: HTTP_STATUS.BAD_REQUEST,
            message: CommonMessage.INVALID_PARAMS
        }],
        [AppError, {
            type: 'APPLICATION_ERROR',
            level: 'warn',
            code: HTTP_STATUS.BAD_REQUEST,
            message: CommonMessage.SERVER_ERROR
        }]
    ]);

    // 查找错误配置
    let errorConfig = errorConfigMap.get(Object.getPrototypeOf(error).constructor);
    
    // 处理未匹配的系统错误
    if (!errorConfig) {
        errorConfig = {
            type: 'SYSTEM_ERROR',
            level: 'error',
            code: error.code === 'ER_DUP_ENTRY' ? HTTP_STATUS.CONFLICT : HTTP_STATUS.INTERNAL_ERROR,
            message: error.code === 'ER_DUP_ENTRY' ? CommonMessage.DUPLICATE_ERROR : CommonMessage.SERVER_ERROR
        };
    }

    // 应用错误配置
    const { type: errorType, level: logLevel, code: statusCode, message: defaultMessage } = errorConfig;
    const responseMessage = error.message || defaultMessage;

    // 记录错误日志
    logger[logLevel](errorType, errorContext);

    return {
        error,
        errorContext,
        statusCode: error.code || statusCode,
        message: responseMessage
    };
}

export function errorHandler(err, req, res, next) {
    // 错误边界保护
    if (res.headersSent) {
        return next(err);
    }
    
    // 处理错误并获取响应数据
    const { error, errorContext, statusCode, message } = handleError(err, 'HTTP_REQUEST', {
        path: req.path,
        method: req.method,
        userId: req.user?.id,
        requestId: req.id // 假设请求ID已在其他中间件中设置
    });

    // 构建错误响应数据
    const responseData = error instanceof ValidationError ? {
        details: error.details,
        validationErrors: error.validationErrors
    } : error.data || null;

    // 发送标准化响应
    return ResponseHandler.send(
        res,
        responseData,
        message,
        statusCode,
        errorContext
    );
}